package com.rabbiter.si.service;

import com.rabbiter.si.common.ExcelUtils;
import com.rabbiter.si.entity.ImportResult;
import com.rabbiter.si.entity.StudentGrade;
import com.rabbiter.si.mapper.StudentGradeMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;

@Service
@Slf4j
public class GradeService {
    @Autowired
    private StudentGradeMapper gradeMapper;

    // 导入成绩
    @Transactional
    public ImportResult importGrades(MultipartFile file) {
        ImportResult result = new ImportResult();

        try {
            // 解析Excel文件
            List<StudentGrade> grades = ExcelUtils.importFromExcel(file.getInputStream());

            // 数据校验与导入
            for (StudentGrade grade : grades) {
                // 基础校验
                if (grade.getScore() == null || grade.getScore() < 0 || grade.getScore() > 100) {
                    result.addError("成绩无效: " + grade.getStudentName() + "(" + grade.getStudentId() + "), 课程: " + grade.getCourseName());
                    continue;
                }

                // 检查学生ID和课程ID是否为空
                if (StringUtils.isEmpty(grade.getStudentId()) || StringUtils.isEmpty(grade.getCourseId())) {
                    result.addError("学号或课程ID为空: " + grade.getStudentName() + "(" + grade.getStudentId() + "), 课程: " + grade.getCourseName());
                    continue;
                }

                // 检查记录是否存在
                int count = gradeMapper.countByUniqueKey(
                        grade.getStudentId(), grade.getCourseId(), grade.getTerm());

                if (count > 0) {
                    // 更新现有记录
                    int updateResult = gradeMapper.update(grade);
                    if (updateResult > 0) {
                        result.incrementUpdated();
                    } else {
                        result.addError("更新失败: " + grade.getStudentName() + "(" + grade.getStudentId() + "), 课程: " + grade.getCourseName());
                    }
                } else {
                    // 插入新记录
                    int insertResult = gradeMapper.insert(grade);
                    if (insertResult > 0) {
                        result.incrementAdded();
                    } else {
                        result.addError("插入失败: " + grade.getStudentName() + "(" + grade.getStudentId() + "), 课程: " + grade.getCourseName());
                    }
                }
            }
        } catch (Exception e) {
            result.addError("导入过程发生异常: " + e.getMessage());
            log.error("成绩导入异常", e);
        }

        return result;
    }

    public List<StudentGrade> getAllGrades() {
        return gradeMapper.selectAll();
    }
}